﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

using ERPStore.Extensions;

namespace ERPStore.Web.Controllers.ActionFilters
{
	public class PrivateActionFilter : ActionFilterAttribute
	{
		public PrivateActionFilter()
		{
		}

		public override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			var privateUrlList = GetPrivateUrlList(filterContext.HttpContext);

			if (!filterContext.IsChildAction
				&& !filterContext.RequestContext.HttpContext.User.Identity.IsAuthenticated
				&& IsPrivateUrl(filterContext.HttpContext.Request.RawUrl, privateUrlList))
			{
				string url = string.Format("/compte/connexion?returnUrl={0}", filterContext.HttpContext.Request.RawUrl);
				filterContext.HttpContext.Response.BufferOutput = true;
				filterContext.HttpContext.Response.Redirect(url, true);
				return;
			}
			base.OnActionExecuting(filterContext);
		}

		private IList<PrivateUrl> GetPrivateUrlList(System.Web.HttpContextBase context)
		{
			var key = "PrivateUrlList";
			var cacheService = GlobalConfiguration.Configuration.DependencyResolver.GetService<ERPStore.Services.ICacheService>();
			var list = cacheService[key] as IList<PrivateUrl>;
			if (list == null)
			{
				var serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<PrivateUrl>));
				var fileName = System.IO.Path.Combine(context.Server.MapPath("/"), "privateurls.config");
				if (!System.IO.File.Exists(fileName))
				{
					list = new List<PrivateUrl>();
					list.Add(new PrivateUrl() { PatternUrl = "regexpattern" });
					using(var ms = new System.IO.MemoryStream())
					{
						serializer.Serialize(ms, list);
						System.IO.File.WriteAllBytes(fileName, ms.GetBuffer());
						ms.Close();
					}
				}
				else
				{
					var buffer = System.IO.File.ReadAllBytes(fileName);
					using (var ms = new System.IO.MemoryStream(buffer))
					{
						list = (List<PrivateUrl>)serializer.Deserialize(ms);
					}
				}
				cacheService.Add(key, list, DateTime.Now.AddDays(1));
			}

			return list;
		}

		private bool IsPrivateUrl(string url, IList<PrivateUrl> list)
		{
			foreach (var item in list)
			{
				var match = System.Text.RegularExpressions.Regex.IsMatch(url, item.PatternUrl);
				if (match)
				{
					return true;
				}
			}
			return false;
		}
	}
}
